package com.liu.stockmarket.repository.database

import com.liu.stockmarket.repository.database.dao.TransactionRecordDao
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import java.time.LocalDate

class TransactionRecordRepository(
    private val transactionRecordDao: TransactionRecordDao
) {

    val allTransactionRecords = transactionRecordDao.queryAllFlow()

    fun queryByStockId(stockId: Long): Flow<List<TransactionRecordEntity>> =
        transactionRecordDao.queryByStockIdDistinctUntilChanged(stockId)

    suspend fun save(transactionRecordEntity: TransactionRecordEntity):Boolean {
        return withContext(Dispatchers.IO){
            transactionRecordDao.save(transactionRecordEntity)
            true
        }

    }

    /**
     * 选择全部
     */

    suspend fun queryAll(): List<TransactionRecordEntity> = transactionRecordDao.queryAll()
    suspend fun deleteAllForSaveAll(datas: List<TransactionRecordEntity>) {
        transactionRecordDao.deleteAllForSaveAll(datas)
    }

    suspend fun deleteAll() {
        transactionRecordDao.deleteAll()
    }

    /**
     * 查询某日的交易记录
     */
    suspend fun queryTodayTransactionRecord(date: LocalDate) =
        transactionRecordDao.queryTodayTransactionRecord(date)

    suspend fun queryTodayTransactionRecordByStockId(stockId: Long, date: LocalDate) =
        transactionRecordDao.queryTodayTransactionRecordByStockId(stockId, date)
}